package com.briup.jd2407cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.briup.jd2407cms.domain.User;
import com.briup.jd2407cms.domain.extend.UserExtend;
import com.briup.jd2407cms.exception.ServiceException;
import com.briup.jd2407cms.service.UserService;
import com.briup.jd2407cms.mapper.UserMapper;
import com.briup.jd2407cms.util.MD5Utils;
import com.briup.jd2407cms.util.result.ResultCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.Collection;

/**
* @author jay
* @description 针对表【cms_user】的数据库操作Service实现
* @createDate 2024-11-18 14:40:14
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
    implements UserService{
    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public User prelogin(String username, String password) {
        //1.条件准备
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, username)
                .eq(User::getPassword, password)
                .eq(User::getDeleted, 0);
        //2.查询校验
        User user = userMapper.selectOne(lqw);
        if (user == null) {
            log.error("账号不存在或密码错误");
            throw new ServiceException(ResultCode.USER_LOGIN_ERROR);
        }
        return user;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public IPage<UserExtend> query(Integer pageNum, Integer pageSize,
                                   String username, String status, Integer roleId, Integer isVip) {
        IPage<UserExtend> page = new Page<>(pageNum, pageSize);
        IPage<UserExtend> userExtends = userMapper.selectByPage(page, username, status, roleId, isVip);
        System.out.println("userExtends = " + userExtends);
        return userExtends;
    }

    // 新增用户：username存在不为空且唯一 password不为空
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean save(User user) {
        // MD5加密
        user.setPassword(MD5Utils.MD5(user.getPassword()));

        // 1、判断username、password是否存在且不为空
        String username = user.getUsername();
        String password = user.getPassword();
        // 1.1 null值判断
        if (username == null || password == null) {
            log.error("用户名或密码为null");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }
        // 1.2 空值判断 “”、“ ”、“   ”、“\t”
        username = username.trim();
        password = password.trim();
        if (username.isEmpty() || password.isEmpty()) {
            log.error("用户名或密码为空");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }
        // 1.3 修改user中username、password值
        user.setUsername(username);
        user.setPassword(password);

        // 2、判断username是否唯一
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername, username).eq(User::getDeleted, 0);
        if (userMapper.selectCount(lqw) != 0) {
            log.error("新增用户时，用户名已存在");
            throw new ServiceException(ResultCode.USERNAME_HAS_EXISTED);
        }
        // 3、补充注册时间
        user.setRegisterTime(LocalDateTime.now());
        return super.save(user);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateById(User user) {
        // 1、id判断（非空且有效存在）
        String uid = user.getId();
        User uuser = userMapper.selectById(uid);
        if (uid == null || uuser == null) {
            log.error("更新时，用户id为null或无效");
            throw new ServiceException(ResultCode.PARAM_IS_INVALID);
        }
        // 2、username空白字符去除
        String username = user.getUsername(); // 传入的
        String uusername = uuser.getUsername(); // 数据库中的
        if (username != null && !(username).equals(uusername)){
            String trim = username.trim();
            if (trim.isEmpty()) {
                log.error("更新时，用户名为空或无效");
                throw new ServiceException(ResultCode.PARAM_IS_INVALID);
            }
            // 更新username(已经去除前后空白字符)
            user.setUsername(trim);

            //3.用户名唯一判断: 查询username是否唯一(除当前user外)
            if (userMapper.selectCount(
                    new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, trim)) != 0) {
                log.error("用户名已存在");
                throw new ServiceException(ResultCode.USERNAME_HAS_EXISTED);
            }
        }
        return super.updateById(user);
    }

    @Override
    public boolean removeByIds(Collection<? extends Serializable> ids) {
        //1.有效参数判断
        if (ids == null || ids.isEmpty()) {
            log.error("删除用户时，传入的用户id无效");
            throw new ServiceException(ResultCode.PARAM_IS_BLANK);
        }
        return super.removeByIds(ids);
    }
}




